package com.andromouse;

import java.awt.TrayIcon;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer implements Runnable {
	private static TrayIcon trayIcon;
	public DatagramSocket socket;
	static final int BUFSIZE = 1024;
	String clientSentence = null;
	int PORT = Utils.port;
	Thread thread;

	public UDPServer(DatagramSocket s) {
		this.socket = s;
	}

	public static void trayMessage(String message) {
		trayIcon.displayMessage("AndroMouse Server", message,
				TrayIcon.MessageType.INFO);
	}

	public void run() {
		while (true)
			try {
				byte[] buffer = new byte[1024];
				DatagramPacket packet = new DatagramPacket(buffer,
						buffer.length);
				this.socket.receive(packet);
				this.clientSentence = new String(packet.getData());
				if (this.clientSentence.contains("AMSNIFF")) {
					byte[] sendData = "GOTBACK".getBytes();
					InetAddress IPAddress = packet.getAddress();
					this.PORT = packet.getPort();
					DatagramPacket sendPacket = new DatagramPacket(sendData,
							sendData.length, IPAddress, this.PORT);
					this.socket.send(sendPacket);
				} else if (this.clientSentence.contains("AMSCREEN")) {
					Runnable run = new ScreenServer(packet.getAddress()
							.getHostAddress());
					this.thread = new Thread(run);
					this.thread.start();
				} else if (this.clientSentence.contains("AMSCREENCLOSE")) {
					this.thread.stop();
				} else {
					CommandHandle handleThis = new CommandHandle(
							this.clientSentence);
					handleThis.handle();
				}

				this.clientSentence = "";
				continue;
			} catch (IOException e) {
				System.out.println("wrong here");
				e.printStackTrace();
				this.socket.close();
				continue;
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
}
